package com.praveen.reminder;

import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Map;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.format.DateFormat;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

public class CreateNewActivity extends Activity {
	@SuppressWarnings("unused")
	private final static String LOGTAG = "CreateNewActivity";
	private final static int wordLimit = 50;
	private int mEntryNo;
	private TextView mDateDisplay;
	private TextView mTimeDisplay;
	private TextView mCharRemaining;
	private Button mPickDate;
	private Button mPickTime;
	private Button mSave;
	private Button mCancel;
	private EditText mReminder;
	private ReminderData mData;
	private ReminderApplication mApp;
	private Button mRepeat;
	private TextView mRepeatFreqDisplay;
	
	private class TimePickerFragment extends DialogFragment implements TimePickerDialog.OnTimeSetListener {
    	@Override
    	public Dialog onCreateDialog(Bundle savedInstanceState) {
    		return new TimePickerDialog(getActivity(), this, mData.getmHour(), mData.getmMinute(), DateFormat.is24HourFormat(getActivity()));
    	}

    	public void onTimeSet(TimePicker view, int hour, int minute) {
    		updateTimeDisplayAndData(hour, minute);
    	}
    }
	
	private class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {
		@Override
		public Dialog onCreateDialog(Bundle savedInstanceState) {
			return new DatePickerDialog(getActivity(), this, mData.getmYear(), mData.getmMonth() - 1, mData.getmDay());
		}

		public void onDateSet(DatePicker view, int year, int month, int day) {
			updateDateDisplayAndData(year, month + 1, day);
		}
	}
	
	private class RepeatFreqDialogFragment extends DialogFragment {
		@Override
		public Dialog onCreateDialog(Bundle savedInstanceState) {
			final CharSequence[] items = {"Once", "Daily", "Weekly", "Monthly", "Yearly"};
			AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
			builder.setTitle("Set Repeat Interval");
			builder.setSingleChoiceItems(items, CreateNewActivity.this.mData.getmRepeatFreq(), new DialogInterface.OnClickListener() {
			    public void onClick(DialogInterface dialog, int item) {
			    	CreateNewActivity.this.mRepeatFreqDisplay.setText(items[item]);
			    	CreateNewActivity.this.mData.setmRepeatFreq(item);
			    }
			});
			return builder.create();
		}
	}
	
	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.createnew);
        mDateDisplay = (TextView)findViewById(R.id.dateText);
        mTimeDisplay = (TextView)findViewById(R.id.timeText);
        mPickDate = (Button)findViewById(R.id.setDate);
        mPickTime = (Button)findViewById(R.id.setTime);
        mSave = (Button)findViewById(R.id.save);
        mCancel = (Button)findViewById(R.id.cancel);
        mReminder = (EditText)findViewById(R.id.reminderText);
        mApp = (ReminderApplication)getApplication();
        mData = new ReminderData();
        mData.setmRepeatFreq(ReminderApplication.REPEAT_ONCE);
        mCharRemaining = (TextView)findViewById(R.id.textLen);
        mCharRemaining.setText(Integer.toString(wordLimit));
        mEntryNo = mApp.getmMaxEntryNo();
        mRepeatFreqDisplay = (TextView)findViewById(R.id.repeatFreqTextView);
        mRepeat = (Button)findViewById(R.id.setRepeat);
        mRepeatFreqDisplay.setText("Once");

        mReminder.addTextChangedListener(new TextWatcher() {		
			public void onTextChanged(CharSequence s, int start, int before, int count) {}
			
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
			
			public void afterTextChanged(Editable s) {
				int textCount = wordLimit - s.length();
				mCharRemaining.setText(Integer.toString(textCount));
				if(textCount < 0) {
					s.replace(wordLimit, s.length(), "");
				}
			}
		});
        
        mPickDate.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				DialogFragment newFragment = new DatePickerFragment();
			    newFragment.show(getFragmentManager(), "datePicker");
            }
        });
        
        mPickTime.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				DialogFragment newFragment = new TimePickerFragment();
			    newFragment.show(getFragmentManager(), "timePicker");
            }
        });
        
        mRepeat.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				DialogFragment newFragment = new RepeatFreqDialogFragment();
			    newFragment.show(getFragmentManager(), "setRepeat");
			}
        });
        
        mSave.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				if(!checkIfValidDateAndTime()) {
					return;
				}
				mEntryNo++;
				mApp.setmMaxEntryNo(mEntryNo);
				mData.setmReminderText(mReminder.getText().toString());
				mData.setmEntryNo(mEntryNo);
				createScheduledNotification();
				Pair<Integer, String> pair = mData.makeKey();
				mApp.addToMap(pair, mReminder.getText().toString());
				Map<Pair<Integer, String>, String>map = mApp.getMap();
				int pos = 0;
				for(Map.Entry<Pair<Integer, String>, String>entry : map.entrySet()) {
					if (pair.getSecond().compareTo(entry.getKey().getSecond()) == 0) {
						break;
					}
					pos++;
				}
				mApp.addToDataList(mData, pos);
				mApp.getFileManager().appendNewDataNode(mData);
				setResult(RESULT_OK);
				CreateNewActivity.this.finish();
			}
        });
        
        mCancel.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				setResult(RESULT_CANCELED);
				CreateNewActivity.this.finish();
			}
        });
        updateDateAndTimeToCurrent();
	}
	
	private void createScheduledNotification() {
		GregorianCalendar gc = new GregorianCalendar (mData.getmYear(), mData.getmMonth() - 1, mData.getmDay(), mData.getmHour(), mData.getmMinute());
		AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
		Intent intent = new Intent(this, NotificationSenderBroadcastReceiver.class);
		intent.putExtra("com.praveen.reminder.CreateNewActivity", mData.getmEntryNo());
		intent.putExtra("com.praveen.reminder.CreateNewActivity", mData.getmReminderText());
		PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), mData.getmEntryNo(), intent, PendingIntent.FLAG_UPDATE_CURRENT);
		alarmManager.set(AlarmManager.RTC_WAKEUP, gc.getTimeInMillis(), pendingIntent);
	}
	
	private boolean checkIfValidDateAndTime() {
		int res = Utility.isPast(mData, mApp);
		if (res == ReminderApplication.DATE_ERROR) {
			Toast.makeText(getBaseContext(), "Date cannot be lesser than current date", Toast.LENGTH_LONG).show();
			return false;
		}
		else if (res == ReminderApplication.TIME_ERROR) {
			Toast.makeText(getBaseContext(), "Time cannot be lesser than current time", Toast.LENGTH_LONG).show();
			return false;
		}
		else
			return true;
	}
	
	private void updateDateAndTimeToCurrent() {
		final Calendar c = Calendar.getInstance();
		updateDateDisplayAndData(c.get(Calendar.YEAR), c.get(Calendar.MONTH) + 1, c.get(Calendar.DAY_OF_MONTH));
        updateTimeDisplayAndData(c.get(Calendar.HOUR_OF_DAY), c.get(Calendar.MINUTE));
	}
	
	private void updateDateDisplayAndData(int year, int month, int day) {
		mData.setmDay(day);
		mData.setmMonth(month);
		mData.setmYear(year);
		mDateDisplay.setText(new StringBuilder().append(Utility.pad(day)).append("-").append(Utility.pad(month)).append("-").append(year).append(" "));
	}
	
	private void updateTimeDisplayAndData(int hour, int minute) {
		mData.setmHour(hour);
		mData.setmMinute(minute);
		mTimeDisplay.setText(new StringBuilder().append(Utility.pad(hour)).append(":").append(Utility.pad(minute)));
	}
}
